<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}头条自动发文系统{% endblock %}</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            color: white;
            background-color: rgba(255,255,255,0.2);
            transform: translateX(5px);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            transition: all 0.3s ease;
        }
        .card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }
        .btn-gradient {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            color: white;
        }
        .btn-gradient:hover {
            background: linear-gradient(45deg, #764ba2, #667eea);
            color: white;
        }
        .status-badge {
            font-size: 0.75rem;
        }
        .user-info {
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .loading {
            display: none;
        }
        .loading.show {
            display: inline-block;
        }
        .nav-link.disabled {
            opacity: 0.5;
            cursor: not-allowed !important;
        }
        .btn.disabled {
            opacity: 0.5;
            cursor: not-allowed !important;
        }
        .connection-status {
            transition: all 0.3s ease;
        }
        .connection-indicator {
            transition: background-color 0.3s ease;
        }
    </style>
    
    {% block extra_css %}{% endblock %}
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4 class="text-white">
                            <i class="fas fa-newspaper"></i>
                            头条发文系统
                        </h4>
                    </div>
                    
                    <!-- 连接状态指示器 -->
                    <div class="connection-status mb-3 p-2 rounded" style="background: rgba(255,255,255,0.1);">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <div id="connection-indicator" class="rounded-circle me-2" style="width: 12px; height: 12px; background-color: #6c757d;"></div>
                                <small id="connection-text" class="text-light">检测中...</small>
                            </div>
                            <div id="reconnect-actions" style="display: none;">
                                <button id="reconnect-btn" class="btn btn-sm btn-outline-light me-1" title="重新连接">
                                    <i class="fas fa-link"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 用户信息 -->
                    {% if account %}
                    <div class="user-info text-white">
                        <div class="d-flex align-items-center">
                            {% if account.avatar_url %}
                            <img src="{{ account.avatar_url }}" alt="头像" class="rounded-circle me-2" width="40" height="40">
                            {% else %}
                            <div class="rounded-circle bg-secondary d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                                <i class="fas fa-user text-white"></i>
                            </div>
                            {% endif %}
                            <div>
                                <div class="fw-bold">{{ account.nickname or account.username }}</div>
                                <small class="text-light" id="login-status">已登录</small>
                            </div>
                        </div>
                    </div>
                    {% else %}
                    <div class="user-info text-white" id="no-account-info">
                        <div class="text-center">
                            <i class="fas fa-user-slash fa-2x mb-2 text-muted"></i>
                            <div class="text-muted">未登录</div>
                        </div>
                    </div>
                    {% endif %}
                    
                    <!-- 导航菜单 -->
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <i class="fas fa-home me-2"></i>
                                首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/login">
                                <i class="fas fa-sign-in-alt me-2"></i>
                                账号登录
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/generate">
                                <i class="fas fa-magic me-2"></i>
                                生成文章
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/publish">
                                <i class="fas fa-paper-plane me-2"></i>
                                发布文章
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/monitor">
                                <i class="fas fa-chart-line me-2"></i>
                                数据监控
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/settings">
                                <i class="fas fa-cog me-2"></i>
                                系统设置
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <div class="pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">{% block page_title %}首页{% endblock %}</h1>
                </div>
                
                <!-- 消息提示 -->
                <div id="alert-container"></div>
                
                {% block content %}{% endblock %}
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        // 通用工具函数
        function showAlert(message, type = 'info', duration = 5000) {
            const alertHtml = `
                <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            $('#alert-container').append(alertHtml);
            
            // 自动关闭
            setTimeout(() => {
                $('.alert').last().fadeOut(() => {
                    $(this).remove();
                });
            }, duration);
        }
        
        function showLoading(element, show = true) {
            const $element = $(element);
            if (show) {
                $element.prop('disabled', true);
                $element.find('.loading').addClass('show');
            } else {
                $element.prop('disabled', false);
                $element.find('.loading').removeClass('show');
            }
        }
        
        // 全局连接状态
        let isConnected = false;
        let isLoggedIn = false;
        let connectionCheckInterval = null;
        
        // 检查连接状态
        function checkConnectionStatus() {
            $.get('/api/connection-status')
                .done(function(response) {
                    if (response.success) {
                        updateConnectionStatus(response.browser_connected, response.is_logged_in, response.message, response.user_info);
                    } else {
                        updateConnectionStatus(false, false, response.message, null);
                    }
                })
                .fail(function() {
                    updateConnectionStatus(false, false, '连接检测失败', null);
                });
        }
        
        // 更新连接状态显示
        function updateConnectionStatus(connected, loggedIn, message, userInfo) {
            isConnected = connected;
            isLoggedIn = loggedIn;
            
            const $indicator = $('#connection-indicator');
            const $text = $('#connection-text');
            const $reconnectActions = $('#reconnect-actions');
            const $loginStatus = $('#login-status');
            
            if (connected && loggedIn) {
                // 已连接且已登录
                $indicator.css('background-color', '#28a745'); // 绿色
                $text.text('已连接已登录');
                $reconnectActions.hide();
                
                // 更新用户信息显示
                if (userInfo && userInfo.username) {
                    $loginStatus.text(`已登录 - ${userInfo.username}`);
                    // 如果有用户信息区域，也更新它
                    updateUserInfoDisplay(userInfo);
                } else {
                    $loginStatus.text('已登录');
                }
                
                enableAllFunctions();
            } else if (connected && !loggedIn) {
                // 已连接但未登录
                $indicator.css('background-color', '#ffc107'); // 黄色
                $text.text('已连接未登录');
                $reconnectActions.hide();
                $loginStatus.text('未登录');
                disableDataFunctions();
                // 显示登录提示
                showAlert('浏览器已连接，请前往登录页面进行登录', 'info', 8000);
            } else {
                // 连接断开
                $indicator.css('background-color', '#dc3545'); // 红色
                $text.text('连接断开');
                $reconnectActions.show();
                $loginStatus.text('连接断开');
                disableAllFunctions();
                // 显示重连提示
                showAlert('浏览器连接已断开，请点击重新连接按钮', 'warning', 10000);
            }
        }
        
        // 更新用户信息显示
        function updateUserInfoDisplay(userInfo) {
            if (!userInfo) return;
            
            // 更新用户名显示
            if (userInfo.username) {
                $('.user-info .fw-bold').text(userInfo.nickname || userInfo.username);
            }
            
            // 更新头像显示
            if (userInfo.avatar_url) {
                $('.user-info img').attr('src', userInfo.avatar_url);
            }
        }
        
        // 启用所有功能
        function enableAllFunctions() {
            $('.nav-link').removeClass('disabled').css('pointer-events', 'auto');
            $('button:not(#reconnect-btn)').prop('disabled', false);
            $('.btn').removeClass('disabled');
        }
        
        // 禁用数据相关功能（保留登录功能）
        function disableDataFunctions() {
            // 禁用除登录外的其他功能
            $('.nav-link[href="/generate"], .nav-link[href="/publish"], .nav-link[href="/monitor"]')
                .addClass('disabled').css('pointer-events', 'none');
        }
        
        // 禁用所有功能
        function disableAllFunctions() {
            $('.nav-link:not([href="/login"])').addClass('disabled').css('pointer-events', 'none');
            $('button:not(#reconnect-btn)').prop('disabled', true);
            $('.btn:not(#reconnect-btn)').addClass('disabled');
        }
        
        // 重连按钮点击事件
        $('#reconnect-btn').click(function() {
            showLoading(this, true);
            
            $.post('/api/reconnect-browser')
                .done(function(response) {
                    if (response.success) {
                        showAlert(response.message, 'success');
                        
                        // 重连成功后检查连接状态
                        setTimeout(() => {
                            checkConnectionStatus();
                            
                            // 如果需要登录，跳转到登录页面
                            if (!response.is_logged_in && window.location.pathname !== '/login') {
                                setTimeout(() => {
                                    showAlert('浏览器连接成功，正在跳转到登录页面...', 'info');
                                    window.location.href = '/login';
                                }, 1000);
                            }
                        }, 1000);
                    } else {
                        showAlert(response.message, 'danger');
                    }
                })
                .fail(function() {
                    showAlert('重新连接失败，请重试', 'danger');
                })
                .always(function() {
                    showLoading($('#reconnect-btn'), false);
                });
        });
        
        // 启动连接状态检测
        function startConnectionCheck() {
            // 立即检测一次
            checkConnectionStatus();
            
            // 每10秒检测一次
            connectionCheckInterval = setInterval(checkConnectionStatus, 10000);
        }
        
        // 停止连接状态检测
        function stopConnectionCheck() {
            if (connectionCheckInterval) {
                clearInterval(connectionCheckInterval);
                connectionCheckInterval = null;
            }
        }
        
        // 页面可见性变化时的处理
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                stopConnectionCheck();
            } else {
                startConnectionCheck();
            }
        });
        
        // 设置当前页面的导航高亮
        $(document).ready(function() {
            const currentPath = window.location.pathname;
            $('.sidebar .nav-link').each(function() {
                if ($(this).attr('href') === currentPath) {
                    $(this).addClass('active');
                }
            });
            
            // 启动连接状态检测
            startConnectionCheck();
        });
    </script>
    
    {% block extra_js %}{% endblock %}
</body>
</html>
